'use strict';

var pcConfig = {
	'iceServers':[{
		'url':'stun:stun.l.google.com:19302'
	}]
}

var sdpConstraints = {
	'mandatory':{
		'OfferToReceiveAudio':true,
		'OfferToReceiveVideo':true
	}
}

var server = null;
var pcConstraint = null;
var isChannelReady = false;
var dataConstraint = null;

//创造者标识
//var inventor = false;


function initialise(mediaObj){
	navigator.mediaDevices.getUserMedia(mediaObj).then(init_success,init_error).catch(function(e){
		console.log("获取媒体资源时出错");
		console.log(e);
	});
}

function init_success(stream){
	vm.localVideo = window.URL.createObjectURL(stream);
	vm.localStream = stream;
	vm.startBtn = true;
	vm.callBtn = false;
}

function init_error(err){
	console.log("失败");
}

function createPeerConnectionAndDataChannel(){
	/*vm.local = new RTCPeerConnection(server,pcConstraint);*/
	vm.local = new RTCPeerConnection(pcConfig);
	
	vm.local.onicecandidate = handleIceCandidate;
	vm.local.onicecandidatestatechange = onIceStateChange;
	vm.local.onaddstream = handleRemoteStreamAdded;
	vm.local.onremovestream = handleRemoteStreamRemoved;
	
	vm.sendChannel = vm.local.createDataChannel("sendDataChannel",dataConstraint);
	vm.sendChannel.onopen = onSendChannelStateChange;
	vm.sendChannel.onclose = onSendChannelStateChange;
	
	vm.local.addStream(vm.localStream);
}

function handleIceCandidate(event){
	console.log("ice candidate事件被触发: ",event);
	console.log(event.candidate);
	if(event.candidate){
		sendMsg("/app/test/message",JSON.stringify({
			"type":"candidate",
			"label":event.candidate.sdpMLineIndex,
			"id":event.candidate.sdpMid,
			"candidate":event.candidate.candidate
			/*"candidate":JSON.stringify(event.candidate)*/
		}));
	}else{
		console.log("End of candidates.");
	}
}

function handleRemoteStreamAdded(event){
	console.log("Added Remote Stream",event);
	vm.remoteVideo = window.URL.createObjectURL(event.stream);
	vm.remoteStream = event.stream;
}

function handleRemoteStreamRemoved(event) {
	  console.log('Remote stream removed. Event: ', event);
}

function onIceStateChange(event){
	console.log("Ice State has change: "+e)
}

function onSendChannelStateChange(){
	console.log("Send Channel State has change: "+sendChannel.readyState);
}

function doCall(){
	console.log("send offer to peer");
	vm.local.createOffer(setLocalAndSendMessage, handleCreateOfferError);
}

function doAnswer(){
	console.log("send answer to peer");
	vm.local.createAnswer().then(
		setLocalAndSendMessage,
		onCreateSessionDescriptionError
	);
}

function handleCreateOfferError(event){
	console.log("createOffer() error: ",event);
}

function setLocalAndSendMessage(sessionDescription) {
  // Set Opus as the preferred codec in SDP if Opus is present.
  //  sessionDescription.sdp = preferOpus(sessionDescription.sdp);
  vm.local.setLocalDescription(sessionDescription);
  console.log('setLocalAndSendMessage sending message', sessionDescription);
  sendMsg("/app/test/message",JSON.stringify(sessionDescription));
}

function onCreateSessionDescriptionError(error) {
  console.log('Failed to create session description: ' + error.toString());
}

function closeWebRTC(){
	/*vm.localVideo = null;
	vm.localStream.close();*/
	vm.local.close();
	vm.sendChannel.close();
}